/*
 * OpenTicketsListDialog.java
 *
 * Created on September 8, 2006, 12:04 AM
 */
package com.floreantpos.ui.dialog;

import com.floreantpos.config.PrintConfig;
import com.floreantpos.jreports.JReportPrintService;
import com.floreantpos.main.Application;
import com.floreantpos.model.ActionHistory;
import com.floreantpos.model.Ticket;
import com.floreantpos.model.User;
import com.floreantpos.model.dao.ActionHistoryDAO;
import com.floreantpos.model.dao.TicketDAO;
import com.floreantpos.print.PrinterType;
import java.awt.Component;
import java.awt.Font;
import java.awt.Rectangle;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

/**
 *
 * @author MShahriar
 */
public class OpenTicketsListDialog extends POSDialog {

  private List<Ticket> openTickets;
  private OpenTicketListTableModel tableModel;

  /**
   * Creates new form OpenTicketsListDialog
   */
  public OpenTicketsListDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal, false);
    initComponents();

    if (PrintConfig.isPrintReceiptEnabled()) {
      btnPrint.setEnabled(true);
    } else {
      btnPrint.setEnabled(false);
    }

    setTitle(com.floreantpos.POSConstants.ACTIVE_TICKETS);
    titlePanel.setTitle(com.floreantpos.POSConstants.OPEN_TICKETS_AND_ACTIVITY);

    TicketDAO dao = new TicketDAO();
    openTickets = dao.findOpenTickets();

    tableModel = new OpenTicketListTableModel();
    openTicketListTable.setModel(tableModel);
    openTicketListTable.setDefaultRenderer(Object.class, new TicketTableCellRenderer());
    openTicketListTable.setRowHeight(40);

    selectionModel = new DefaultListSelectionModel();
    selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    openTicketListTable.setSelectionModel(selectionModel);
  }

  private void initComponents() {
    titlePanel = new com.floreantpos.ui.TitlePanel();
    transparentPanel1 = new com.floreantpos.swing.TransparentPanel();
    transparentPanel3 = new com.floreantpos.swing.TransparentPanel();
    btnVoid = new com.floreantpos.swing.PosButton();
    btnPrint = new com.floreantpos.swing.PosButton();
    btnTransferServer = new com.floreantpos.swing.PosButton();
    btnClose = new com.floreantpos.swing.PosButton();
    transparentPanel4 = new com.floreantpos.swing.TransparentPanel();
    btnScrollUp = new com.floreantpos.swing.PosButton();
    btnScrollDown = new com.floreantpos.swing.PosButton();
    transparentPanel2 = new com.floreantpos.swing.TransparentPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    openTicketListTable = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    getContentPane().add(titlePanel, java.awt.BorderLayout.NORTH);

    transparentPanel1.setLayout(new java.awt.BorderLayout());

    transparentPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

    transparentPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 5));

    btnPrint.setText(com.floreantpos.POSConstants.PRINT);
    btnPrint.setPreferredSize(new java.awt.Dimension(100, 50));
    btnPrint.setEnabled(true);
    btnPrint.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        doPrintTicket(evt);
      }
    });

    transparentPanel3.add(btnPrint);

    btnTransferServer.setText("<html><body><center>Transferir<br>Atendente</center></body></html>");
    btnTransferServer.setPreferredSize(new java.awt.Dimension(100, 50));
    btnTransferServer.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        doTransferServer(evt);
      }
    });

    transparentPanel3.add(btnTransferServer);

    btnVoid.setText(com.floreantpos.POSConstants.VOID);
    btnVoid.setPreferredSize(new java.awt.Dimension(100, 50));
    btnVoid.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        doVoidTicket(evt);
      }
    });

    transparentPanel3.add(btnVoid);

    btnClose.setText(com.floreantpos.POSConstants.CLOSE);
    btnClose.setPreferredSize(new java.awt.Dimension(100, 50));
    btnClose.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        doClose(evt);
      }
    });

    transparentPanel3.add(btnClose);

    transparentPanel1.add(transparentPanel3, java.awt.BorderLayout.CENTER);

    transparentPanel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5));
    btnScrollUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/up_32.png")));
    btnScrollUp.setPreferredSize(new java.awt.Dimension(80, 50));
    btnScrollUp.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        doScrollUp(evt);
      }
    });

    transparentPanel4.add(btnScrollUp);

    btnScrollDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/down_32.png")));
    btnScrollDown.setPreferredSize(new java.awt.Dimension(80, 50));
    btnScrollDown.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        doScrollDown(evt);
      }
    });

    transparentPanel4.add(btnScrollDown);

    transparentPanel1.add(transparentPanel4, java.awt.BorderLayout.WEST);

    getContentPane().add(transparentPanel1, java.awt.BorderLayout.SOUTH);

    transparentPanel2.setLayout(new java.awt.BorderLayout(0, 5));

    transparentPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 10, 5, 10));
    openTicketListTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object[][]{},
            new String[]{}
    ));
    jScrollPane1.setViewportView(openTicketListTable);

    transparentPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

    getContentPane().add(transparentPanel2, java.awt.BorderLayout.CENTER);

    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width - 646) / 2, (screenSize.height - 435) / 2, 646, 435);
  }

  private void doScrollUp(java.awt.event.ActionEvent evt) {
    int selectedRow = openTicketListTable.getSelectedRow();
    int rowCount = tableModel.getRowCount();

    if (selectedRow <= 0) {
      selectedRow = rowCount - 1;
    } else if (selectedRow > (rowCount - 1)) {
      selectedRow = rowCount - 1;
    } else {
      --selectedRow;
    }
    openTicketListTable.transferFocus();
    selectionModel.setLeadSelectionIndex(selectedRow);
    Rectangle cellRect = openTicketListTable.getCellRect(selectedRow, 0, false);
    openTicketListTable.scrollRectToVisible(cellRect);
  }

  private void doScrollDown(java.awt.event.ActionEvent evt) {
    int selectedRow = openTicketListTable.getSelectedRow();
    int rowCount = tableModel.getRowCount();

    if (selectedRow < 0) {
      selectedRow = 0;
    } else if (selectedRow >= rowCount - 1) {
      selectedRow = 0;
    } else {
      ++selectedRow;
    }
    openTicketListTable.transferFocus();
    selectionModel.setLeadSelectionIndex(selectedRow);
    Rectangle cellRect = openTicketListTable.getCellRect(selectedRow, 0, false);
    openTicketListTable.scrollRectToVisible(cellRect);
  }

  private Ticket getSelectedTicket() {
    int row = openTicketListTable.getSelectedRow();
    if (row < 0) {
      POSMessageDialog.showError(com.floreantpos.POSConstants.SELECT_TICKET);
      return null;
    }
    return openTickets.get(row);
  }

  private void doClose(java.awt.event.ActionEvent evt) {
    canceled = false;
    dispose();
  }

  private void doTransferServer(java.awt.event.ActionEvent evt) {
    try {
      Ticket ticket = getSelectedTicket();

      if (ticket != null) {
        UserListDialog dialog = new UserListDialog(Application.getPosWindow(), true);
        dialog.open();
        if (!dialog.isCanceled()) {
          User selectedUser = dialog.getSelectedUser();
          if (!ticket.getOwner().equals(selectedUser)) {
            ticket.setOwner(selectedUser);
            TicketDAO.getInstance().update(ticket);
            openTicketListTable.repaint();
          }
        }
      }
    } catch (Exception e) {
      POSMessageDialog.showError(com.floreantpos.POSConstants.ERROR_MESSAGE);
    }
  }

  private void doPrintTicket(java.awt.event.ActionEvent evt) {
    try {
      Ticket ticket = getSelectedTicket();

      if (ticket != null) {
        ticket = TicketDAO.getInstance().initializeTicket(ticket);
        if (PrintConfig.isPrintReceiptEnabled()) {
          try {
            if (PrintConfig.getReceiptPrinterType() == PrinterType.OS_PRINTER) {

              if (!ticket.isPrintedTicket()) {
                ticket.setPrintedTicket(true);
              }

              JReportPrintService.printTicket(ticket);
            }
          } catch (Exception x) {
            POSMessageDialog.showError(com.floreantpos.POSConstants.ERROR_MESSAGE);
          } finally {

          }
        }

        String actionMessage = com.floreantpos.POSConstants.CHK_NO + ticket.getId();
        ActionHistoryDAO.getInstance().saveHistory(Application.getCurrentUser(), ActionHistory.PRINT_CHECK, actionMessage);
      }
    } catch (Exception e) {
      POSMessageDialog.showError(com.floreantpos.POSConstants.ERROR_MESSAGE);
    }
  }

  private void doVoidTicket(java.awt.event.ActionEvent evt) {
    Ticket ticket = getSelectedTicket();
    if (ticket != null) {
      ticket = TicketDAO.getInstance().initializeTicket(ticket);

      VoidTicketDialog dialog = new VoidTicketDialog(Application.getPosWindow(), true);
      dialog.setTicket(ticket);
      dialog.open();

      if (!dialog.isCanceled()) {
        tableModel.removeTicket(ticket);
      }
    }
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new OpenTicketsListDialog(new javax.swing.JFrame(), true).setVisible(true);
      }
    });
  }

  private com.floreantpos.swing.PosButton btnClose;
  private com.floreantpos.swing.PosButton btnPrint;
  private com.floreantpos.swing.PosButton btnScrollDown;
  private com.floreantpos.swing.PosButton btnScrollUp;
  private com.floreantpos.swing.PosButton btnTransferServer;
  private com.floreantpos.swing.PosButton btnVoid;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JTable openTicketListTable;
  private com.floreantpos.ui.TitlePanel titlePanel;
  private com.floreantpos.swing.TransparentPanel transparentPanel1;
  private com.floreantpos.swing.TransparentPanel transparentPanel2;
  private com.floreantpos.swing.TransparentPanel transparentPanel3;
  private com.floreantpos.swing.TransparentPanel transparentPanel4;
  private DefaultListSelectionModel selectionModel;

  class OpenTicketListTableModel extends AbstractTableModel {

    public int getRowCount() {
      if (openTickets == null) {
        return 0;
      }

      return openTickets.size();
    }

    public int getColumnCount() {
      return 5;
    }

    @Override
    public String getColumnName(int column) {
      switch (column) {
        case 0:
          return com.floreantpos.POSConstants.ID;

        case 1:
          return Application.getControlTypeIdentifier();

        case 2:
          return com.floreantpos.POSConstants.SERVER;

        case 3:
          return com.floreantpos.POSConstants.DATE_TIME;

        case 4:
          return com.floreantpos.POSConstants.TOTAL;
      }
      return null;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
      if (openTickets == null) {
        return null;
      }

      Ticket ticket = openTickets.get(rowIndex);

      switch (columnIndex) {
        case 0:
          return Integer.valueOf(ticket.getId());

        case 1:
          return ticket.getGuest();

        case 2:
          return ticket.getOwner().toString();

        case 3:
          return ticket.getCreateDate();

        case 4:
          return Double.valueOf(ticket.getTotalWithGratuity());

      }
      return null;
    }

    void removeTicket(Ticket ticket) {
      openTickets.remove(ticket);
      fireTableDataChanged();
    }
  }

  class TicketTableCellRenderer extends DefaultTableCellRenderer {

    Font font = getFont().deriveFont(Font.BOLD, 12);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", new DecimalFormatSymbols(new Locale("pt", "BR")));
    String currencySymbol = Application.getCurrencySymbol();

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      label.setFont(font);

      if (value instanceof Date) {
        label.setText(dateFormat.format(value));
        label.setHorizontalAlignment(SwingConstants.CENTER);
      } else if (value instanceof Double) {
        label.setText(currencySymbol + decimalFormat.format(((Double) value).doubleValue()));
        label.setHorizontalAlignment(SwingConstants.RIGHT);
      } else {
        label.setHorizontalAlignment(SwingConstants.LEFT);
      }
      return label;
    }
  }
}
